package com.waitingsnow.common.share
{
import com.waitingsnow.common.share.qqMicroBlog.api.Authorize;
import com.waitingsnow.common.share.qqMicroBlog.api.Content;
import com.waitingsnow.common.share.qqMicroBlog.core.WeiboConfig;
import com.waitingsnow.common.share.qqMicroBlog.event.WeiboEvent;
import com.waitingsnow.common.share.qqMicroBlog.operation.IRequestOperation;
import com.waitingsnow.common.share.config.AppInfo;
import com.waitingsnow.common.share.events.ShareEvent;
import com.waitingsnow.common.share.util.DataUtils;
import com.waitingsnow.core.debug.Logger;

import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.LocationChangeEvent;
import flash.media.StageWebView;
import flash.net.FileReference;
import flash.net.URLVariables;
import flash.utils.ByteArray;

/**
 * 分享至QQ
 * @author NeilWang
 *
 */
public class ShareToQQ extends BaseShare
{
    //==========================================================================
    //  Class variables
    //==========================================================================
    
    //==========================================================================
    //  Constructor
    //==========================================================================
    /**
     * Constructs a new <code>ShareToQQ</code> instance.
     *
     */
    public function ShareToQQ()
    {
        init();
    }

    //==========================================================================
    //  Properties
    //==========================================================================
    private var config:WeiboConfig;
    private var request:IRequestOperation;
    private var shareRequest:IRequestOperation;
    private var authorize:Authorize;
    
    //==========================================================================
    //  Methods
    //==========================================================================
    
    /**
     * 初始化 
     * @param parames
     * 
     */    
    private function init():void
    {
        config = WeiboConfig.getInstance();
        config.initialize(AppInfo.QQ_APP_KEY, AppInfo.QQ_APP_SECRET);
        config.dataFormat = "json";
        checkToken();
    }
    
    /**
     * 先从缓存中获取应用ID和应用密钥
     */		
    override public function checkToken():void
    {
        //判断是否已经授权
        if(config.oauthToken != null && config.oauthSecret != null)
        {
            //已经被授权，直接获取数据
            _hasAuthorize = true;
            Logger.debug("腾讯分享已经被授权，直接获取数据");
        }
        else
        {
            //开始获取授权
            startAuth();
        }
    }   
    
    /**
     * 授权
     * 
     */    
    private function startAuth():void
    {
        authorize = new Authorize();
        request = authorize.requestToken();
        request.addEventListener(Event.COMPLETE, 
            requestTokenCompleteHandler);
        request.addEventListener(IOErrorEvent.IO_ERROR, reqIoErrorHandler);
    }
    
    /**
     * 获取accessToken 
     * 
     */    
    private function getAccessToken():void
    {
        var authorURL:String = config.encryptURLBase + 
            "authorize?oauth_token=" + config.tempOauthToken;;
        if (webView == null)
        {
            webView = new StageWebView(); 
        }
        webView.stage = stage;
        webView.viewPort = area;
        webView.loadURL(encodeURI(authorURL));
        webView.addEventListener(Event.COMPLETE, webViewCompleteHandler);
        webView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, 
            webViewChangeHandler);
    }
    
    private var file:FileReference;
    private var mess:String;
    /**
     * 分享 
     * 
     */    
    override public function share(message:String = "", pic:ByteArray=null):void
    {
        mess = message;
        var content:Content = new Content();
        content.uploadPic(message, pic);
        content.addEventListener(WeiboEvent.UPLOAD_PIC_COMPLETE, shareCompleteHandler);
        content.addEventListener(WeiboEvent.UPLOAD_PIC_ERROR, shareErrorHandler);
    }
    
    /**
     * 从地址上获取verifier（授权码） 
     * @param url
     * 
     */    
    private function checkBackUrl(url:String):void
    {
		Logger.debug(url);
        var urlVar:URLVariables = DataUtils.getURLVariables(url);
        var verifier:String = urlVar.v;
        if (verifier && config.tempOauthToken)
        {
            var accReq:IRequestOperation = authorize.accessToken(verifier);
            accReq.addEventListener(Event.COMPLETE, accReqCompleteHandler);
            webView.dispose();
            webView = null;
        }
    }
    
    //==========================================================================
    //  Event Handlers
    //==========================================================================
    private function requestTokenCompleteHandler(event:Event):void
    {
        getAccessToken();
    }
    
    private function reqIoErrorHandler(event:IOErrorEvent):void
    {
		Logger.error(event.text);
    }
    
    private function webViewChangeHandler(event:LocationChangeEvent):void
    {
        checkBackUrl(webView.location);
    }
    
    private function webViewCompleteHandler(event:Event):void
    {
        checkBackUrl(webView.location);
    }
    
    private function accReqCompleteHandler(event:Event):void
    {
        dispatchEvent(new ShareEvent(ShareEvent.AUTHORIZE_COMPLETE));
    }
    
    private function shareCompleteHandler(event:WeiboEvent):void
    {
        dispatchEvent(new ShareEvent(ShareEvent.SHARE_COMPLETE));
    }
    
    private function shareErrorHandler(event:WeiboEvent):void
    {
        dispatchEvent(new ShareEvent(ShareEvent.SHARE_ERROR));
    }
}
}